package user

import (
	"github.com/bgmp/config"
	"github.com/bgmp/handler"
	"github.com/bgmp/middleware"
	"github.com/bgmp/model"
	"github.com/gin-gonic/gin"
)

func (b Base) UpdateUserInfo(c *gin.Context, req *UpdateUserInfoRequest) *UpdateUserInfoResponse {
	err := updateUserInfo(req, middleware.GetUserId(c))
	if err != nil {
		handler.Errorf(c, err.Error()) // "更新用户信息失败"
		return nil
	}

	return &UpdateUserInfoResponse{}
}

type UpdateUserInfoRequest struct {
	Username        string            `json:"username"`
	Avatar          string            `json:"avatar"`
	Gender          int8              `json:"gender"`
	Birthday        model.Time        `json:"birthday"`
	Height          float32           `json:"height"`
	Weight          float32           `json:"weight"`
	IllnessDuration float32           `json:"illness_duration"`
	GlucoseUnit     model.GlucoseUnit `json:"glucose_unit"`
}

type UpdateUserInfoResponse struct {
}

func updateUserInfo(req *UpdateUserInfoRequest, id uint) error {
	tx := config.DB.Begin()
	u := &model.User{}
	u.ID = id
	err := u.Get(tx)
	if err != nil { // fail to find the user
		tx.Rollback()
		return err
	}

	if req.Username != "" {
		u.Username = req.Username
	}
	if req.Avatar != "" {
		u.Avatar = req.Avatar
	}
	err = u.Save(tx)
	if err != nil { // fail to save
		tx.Rollback()
		return err
	}

	ud := model.UserDetail{
		UserDetailModel: model.UserDetailModel{
			UserId:          u.ID,
			Gender:          req.Gender,
			Height:          req.Height,
			Weight:          req.Weight,
			IllnessDuration: req.IllnessDuration,
		},
		Birthday:    req.Birthday.Time,
		GlucoseUnit: req.GlucoseUnit,
	}
	err = ud.Update(tx)
	if err != nil { // fail to save
		tx.Rollback()
		return err
	}

	tx.Commit()
	return nil
}
